<?php

namespace App\Http\Controllers\Guard\Login;

use App\Http\Controllers\Common\GuardController;
use App\Models\Common\China;
use App\Models\Constant\UploadConstant;
use App\Models\Rbac\GuardUser;
use App\Models\Rbac\LoginLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class LoginController extends GuardController{

    public function upload2(Request $request){
        $file = $request->file('file');
        $count = $request->input('count',0);
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $size =  $file->getSize();
        $ext = $file->getClientOriginalExtension();
        $originName = $file->getClientOriginalName();
        $module = $request->input('module','default');
        $type = $request->input('type','default');

        //检查目录
        $middlePath = "/$module/".date('Y-m-d');
        $absDir = Storage::disk('upload')->path($middlePath);
        if(!is_dir($absDir)){mkdir($absDir,0777,true);}

        //重命名
        $fileName = time().uniqid().".$ext";

        //如果是图片
        if(in_array($ext, UploadConstant::mapPic)){

            if($request->has('w')){
                $w = $request->input('w');
                $h = $request->input('h');
                if(!empty($w) && !empty($h)){
                    $this->validate($request, [
                        'file' => 'mimes:jpeg,bmp,png,gif,webp|dimensions:width='.$w.',height='.$h,
                    ],[],['w'=>'宽', 'h'=>'高',]);
                }
            }

            $imgIsCut = $request->input('imgIsCut',env('IMG_IS_CUT',false));//是否需要压缩
            $imgIsCutSize = $request->input('imgIsCutSize',env('IMG_IS_CUT_SIZE',1024*1024*1));//压缩阈值
            $imgCutRatio = $request->input('imgCutRatio',env('IMG_CUT_RATION',700));//压缩比

            //如果需要压缩
            if($imgIsCut && $size>=$imgIsCutSize){
                $fileName = time().uniqid().'.jpg';
                $rs = Image::make($file->getRealPath())->resize($imgCutRatio, $imgCutRatio, function ($constraint) {
                    $constraint->aspectRatio();
                })->save($absDir."/$fileName");
                if($rs === false){
                    return responseFail('图片压缩失败');
                }
                $filePath = "$middlePath/$fileName";
            }else{
                $filePath = $file->storeAs($middlePath,$fileName,'upload');
            }
        }
        //如果是文件
        else{
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
        }

        $filePath = Str::replace('//', '/', '/storage/upload/'.$filePath);
        $url = asset($filePath);

        if(in_array($ext, UploadConstant::mapVideo)){
            $url = asset('/common/image/cover.png');
        }
        return response()->json(compact('filePath','url','originName','fileName'),200,[],JSON_UNESCAPED_UNICODE);
    }


    public function login(Request $request) {

        $from = $request->header('from','guard');
        $adminUserName = $request->input('adminUserName');
        $password = $request->input('password');
        $adminUser = (new GuardUser())->getAdminUserByNameAndPwd($adminUserName,md5($password));
        if(!empty($adminUser)){
            $adminUser->token = createNewToken($adminUser->id,$from);
            if(env('IS_WRITE_LOGIN_LOG',false))
                $adminUser->addLoginLog($request->ip(),getOS(),getBrowser());

            if(env('IS_USE_REDIS',false)){
                $key = "token:$from:$adminUser->token";
                if(!Redis::exists($key)){
                    Redis::setex("token:$from",env('TOKEN_LIFE_TIME',120),$adminUser->token);
                }
            }

            return responseSuccess($adminUser->toArray(),1,200000);
        }else{
            return responseFail(200001);
        }
    }

    public function logout(Request $request) {
        $from = $request->header('from');
        $token = $request->header('token');

        if(env('IS_USE_REDIS',false)){
            $key = "token:$from:$token";
            if(Redis::exists($key)){
                Redis::del($key);
            }
        }
        return responseSuccess([],0,200002);
    }

    public function getVerifyCodeImg(Request $request) {
        $w = $request->input('w',150);
        $h = $request->input('h',50);
        $builder  = new CaptchaBuilder();
        $builder->build($w,$h);
        $phrase = $builder->getPhrase();//获取验证码内容
        $request->session()->put('verifyCode',$phrase);
        ob_clean();
        return response($builder->output())->header('Content-type','image/jpeg');
    }

    public function getArea(Request $request) {
        $records = China::where('pcode',0)->with('children')->get();
        $this->handleChildren($records);
        return responseSuccess($records->toArray());
    }
}
